<?php

namespace app\admin\controller\warehouse;

use app\common\controller\Backend;
use app\admin\model\User;
use app\admin\model\in\InInventory as InStoreWarehouse;
use app\admin\model\in\InInventoryDetail;


use TCPDF;
use TCPDFBarcode;
use think\Session;
use think\Db;

/**
 * 入库记录管理
 */
class Ininventory extends Backend
{
    protected $model = null;
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new InStoreWarehouse();

    }

    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
           
            
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
                

            // $sql = $this->model->getLastSql();
            // echo($sql);
            // die();

            // $OutInventoryModel = new OutInventory();
            

           

            $userinfo = $this->auth->getUserInfo();
            $list = collection($list)->toArray();
            $wms = $this->getWarehouse();
            foreach ($list as $key => $value){
                foreach ($wms as $val){
                    if($value['warehouse_code'] == $val['code']){
                        $list[$key]['warehouse_code'] = $val['name'];
                        $list[$key]['contractNo'] = $userinfo['contract_no'];
                    }
                }
                $items = current($this->getInItems($value['inorderid']));
                $list[$key]['items'] = $items['itemname'].' - '.$items['itemsku'].'  *  '.$items['goods_count'];

                $InInventoryDetailModel = new InInventoryDetail();
                $inorderid = $list[$key]['inorderid'];

                // $goods_count = $InInventoryDetailModel->where('orderid',$inorderid)->sum('goods_count');
                // $goods_count = $InInventoryDetailModel->where('orderid',$inorderid)->sum('pw_count');

                $sql = sprintf("select sum(goods_count) as goods_count,sum(pw_count) as pw_count,sum(left_count) as left_count from
                        t_in_inventory_detail where orderid='%s' ",$inorderid);
                        
                $record = Db::query($sql)[0];
                

                $list[$key]['goods_count'] = $record['goods_count'];//申请入库数
                $list[$key]['pw_count']= $record['pw_count'];//已入库数
                $list[$key]['left_count']= $record['left_count'];//未入库数
            }
            $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

            return json($result);
        }

        $wms = $this->getWarehouse();
        $this->view->assign('wms', $wms);
        return $this->view->fetch();
    }

    /**
     * 关联追踪号
     * @param null $ids
     * @return string
     */
    public function addTrackNumber($ids = NULL){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $trackId = isset($params['trackorderid']) ? $params['trackorderid'] : '';
            $kids = isset($params['ids']) ? $params['ids'] : '';
            $pk = $this->model->getPk();//获取主键字段
            $list = $this->model->where($pk, 'in', $kids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $data['id'] = $v['id'];
                $data['trackorderid'] = $trackId;
                $count += $v->save($data);
            }
            if ($count) {
                $this->success();
            } else {
                $this->error("操作失败，稍后重试！");
            }
        }
        $this->view->assign('ids', $ids);
        return $this->view->fetch();

    }

    /**
     * @param $inventoryId
     * @param string $type single|total
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getInItems($inventoryId,$type='single'){
        // $itemInfo = model('InventoryItemInfo');

        $inInventoryDetailModel =  new InInventoryDetail();

        if($type == 'single'){
            $rs = $inInventoryDetailModel->where("orderid","eq",$inventoryId)->limit(0,1)->select();
        }else{
            $rs = $inInventoryDetailModel->where("orderid","eq",$inventoryId)->select();
        }
        $rs = collection($rs)->toArray();

        return $rs;
    }

    /**
     * print
     * @param null $ids
     */
    public function printInventory(){
        $ids =  $this->request->get("ids");
        $info = $this->model->get($ids)->toArray();
        $items = $this->getInItems($info['inorderid'],'total');

        $this->toPdf($info,$items);
    }

    /**
     * 生成入库单PDF文件
     * @param $data
     * @param $items
     */
    public function toPdf($data,$items){

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION,PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle('TCPDF Example 002');
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->SetFont('stsongstdlight', '', 8);
        $pdf->AddPage();

        $style = array(
            'position' => '',
            'align' => 'C',
            'stretch' => false,
            'fitwidth' => true,
            'cellfitalign' => '',
            'border' => false,
            'hpadding' => 'auto',
            'vpadding' => 'auto',
            'fgcolor' => array(0,0,0),
            'bgcolor' => false,
            'text' => true,
            'font' => 'helvetica',
            'fontsize' => 8,
            'stretchtext' => 4
        );
        $style['position'] = 'C';
        $pdf->write1DBarcode($data['inorderid'], 'C39', '', '', '', 25, 0.4, $style, 'N');

        $Inbound = $data['inorderid'];
        $user = Session::get('admin');
        $aid = $user['aid'];
        $date = date('Y-m-d',$data['createtime']);
        $wmsName = $this->getWarehouseName($data['warehouse_code']);
        $title = <<<EOD

                Inbound No: $Inbound
                Package: 1/1
                Uid :$aid
                Create Date :$date
                Warehouse :$wmsName
                
                
EOD;
        $pdf->Write(0, $title, '', 0, 'L', true, 0, false, false, 0);
        $th = <<<EOD
        NO               Prd Name                          SKU#                    QTY                                                                      Bar Code
EOD;
        $pdf->Write(0, $th, '', 0, 'L', true, 0, false, false, 0);


        $style['position'] = 'R';
        foreach ($items as $key => $val){
            $no = $key + 1;
            $itemname = $val['itemname'];
            $itemsku = $val['itemsku'];
            $qty = $val['goods_count'];

        $td = <<<EOD
        $no               $itemname              $itemsku                    $qty  
EOD;
        $pdf->Write(0, $td, '', 0, 'L', true, 0, false, false, 0);
        $pdf->write1DBarcode($itemsku, 'C128', '', '', '', 12, 0.4, $style, 'N');

        }

        //test 表格
//        $tbl = <<<EOD
//        <table border="0" cellpadding="2" cellspacing="2" align="center">
//         <tr nobr="true">
//          <th >NO</th>
//          <th >Prd Name</th>
//          <th >SKU#</th>
//          <th >QTY</th>
//          <th >Bar Code</th>
//         </tr>
//EOD;
//        $trs = '';
//        foreach ($items as $key => $val){
//            $no = $key + 1;
//            $itemname = $val['itemname'];
//            $itemsku = $val['itemsku'];
//            $qty = $val['instoragecount'];
//            $params = $pdf->serializeTCPDFtagParameters(array($itemsku, 'C128', '', '', '', 12, 0.4, $style, 'N'));
//
//            $trs .= "<tr nobr=\"true\" height=\"100px\">
//                    <td>$no</td>
//                    <td>$itemname</td>
//                    <td>$itemsku</td>
//                    <td>$qty</td>
//                    <td>";
//            $trs .= '<tcpdf method="write1DBarcode" params="'.$params.'" />';
//            $pdf->Write(0, $td, '', 0, 'L', true, 0, false, false, 0);
//            $trs.="</td></tr>";
//        }
//        $trs .= "</table>";
//        $tbl .= $trs;
//        $pdf->writeHTML($tbl, true, 12, true, 12);


        $pdf->lastPage();
        $pdf->Output($Inbound.'.pdf', 'D');
    }


    /**
     * 获取商品
     * @return string
     */
    public function items(){
        $id = $this->request->post('id');

        if (!empty($id)) {
            $items = $this->getInItems($id,'total');
            $this->success("请求成功", null, $items);
        }else{
            $this->success("网络异常，稍后重试！", null);
        }
    }

    /**
     * 获取仓库数据
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getWarehouse(){

        $wmsModel = model('Warehouse');
        $wms = $wmsModel->select();
        $wms = collection($wms)->toArray();

        return $wms;
    }
    
    /**
     * 入库编辑
     */
     public function edit($ids = NULL){
      //取到入库记录的主表  

      $inWareHouseModel = new InStoreWarehouse();
      $InInventoryItemModel = new InInventoryDetail();

      $inWareHouseRecord = $inWareHouseModel->where('id',$ids)->find();

      if(intval($inWareHouseRecord['status'])>1){
        $this->error("非待审核状态，不允许编辑!");
        return;
      }

      $InInventoryItemRecord = $InInventoryItemModel->where('orderid',$inWareHouseRecord['inorderid'])->select();
      // $sql = $inWareHouseModel::getLastSql();
      // echo $sql;

      // die();

      $items = collection($InInventoryItemRecord)->toArray();
      $wms = $this->getWarehouse();


      $this->view->assign("items", $items);
      $this->view->assign("wms", $wms);
      return $this->view->fetch();
    }

    /**
     * 查看入库单的入库详情
     *
     * @param [type] $ids
     * @return void
     */
    public function viewDetail($ids=null){
      //取到入库记录的主表  

      $inWareHouseModel = new InStoreWarehouse();
      // $InInventoryItemModel = new InventoryItemInfo;
      $InInventoryItemModel = new InInventoryDetail;

      $inWareHouseRecord = $inWareHouseModel->where('id',$ids)->find();

      $InInventoryItemRecord = $InInventoryItemModel->where('orderid',$inWareHouseRecord['inorderid'])->select();

      $items = collection($InInventoryItemRecord)->toArray();
      $wms = $this->getWarehouse();


      //获取入库单明细
      $inboundList = [];
      $sql = sprintf("SELECT d.main_ref,d.goods_count,d.create_time,g.`name` as itemname,g.`code` as itemsku  
                from t_inbound_bill_detail d 
                INNER JOIN t_inbound_bill m on d.main_ref = m.inbound_no  
                LEFT JOIN t_goods g on d.goods_id= g.id
                WHERE m.inorderid='%s' ",$inWareHouseRecord['inorderid']);
      $inboundList = Db::query($sql);


      // var_dump($items);die();
      $this->view->assign("items", $items);
      $this->view->assign("inboundList",$inboundList);
      $this->view->assign("wms", $wms);
      return $this->view->fetch();
    }

    /**
     * 入库删除
     */
    public function delete($ids=null){
      if ($this->request->isPost()) {
        //1.删除主记录表 2.删除t_inventory_item_info 3.删除t_out_inventory_addr

        try {
          
          $inWareHouseModel = new InStoreWarehouse();
          $InInventoryDetailModel = new InInventoryDetail();

          $inWareHouseRecord = $inWareHouseModel->where('id',$ids)->find();

          if(intval($inWareHouseRecord['status'])>1){
            $this->error('非待审核状态下的入库单不允许删除!');
            return;
          }
          
          Db::startTrans();
         
          $inWareHouseModel->where('id',$ids)->delete(); //删除主记录 t_in_inventory
          $InInventoryDetailModel->where('orderid',$inWareHouseRecord['inorderid'])->delete(); //删除t_inventory_item_info

          Db::commit();
          $this->success('删除成功!');
        } catch (\think\exception\PDOException $e) {
          $this->error($e->getMessage());
        } catch (\think\Exception $e) {
          $this->error($e->getMessage());
        }

      }
    }

    /**
     * @param $warehouseid
     * @return string
     */
    private function getWarehouseName($warehouse_code){

       $warehoues = $this->getWarehouse();
       $name = '';
           foreach ($warehoues as $key => $value){
               if($warehouse_code == $value['code']){
                   $name = $value['name'];
                   break;
               }
           }
           return $name;

    }


}
